﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Reflection;

namespace SQLDB
{
    public class DBToList<T> where T : new()
    {
        public static List<T> DataTableToList(DataTable dt)
        {
            List<T> ts = new List<T>();
            Type type = typeof(T);    //获取T的类型
            String tempName = string.Empty;
            foreach (DataRow row in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pro in propertys)
                {
                    tempName = pro.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pro.CanWrite) continue; //该属性不可写直接跳过
                        object value = row[tempName];
                        if (value != DBNull.Value)
                        {
                            pro.SetValue(t, value, null);
                        }
                    }
                }
                ts.Add(t);
            }

            return ts;
        }
        /// <summary>
        /// DataReader 转换为List
        /// </summary>
        /// <param name="sr"></param>
        /// <returns></returns>
        public static List<T> DataReaderToList(SqlDataReader sr)
        {
            List<T> ts = new List<T>();
            Type type = typeof(T);
            string tempName = string.Empty;
            while (sr.Read())
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pro in propertys)
                {
                    tempName = pro.Name;
                    if (ReaderExist(sr, tempName))
                    {
                        if (!pro.CanWrite) continue;
                        var value = sr[tempName];
                        if (value != DBNull.Value) pro.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        /// <summary>
        /// 判断是否包含 列明
        /// </summary>
        /// <param name="sr"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>
        public static bool ReaderExist(SqlDataReader sr, string columnName)
        {
            int count = sr.FieldCount;
            for (int i = 0; i < count; i++)
            {
                if (sr.GetName(i) == columnName) return true;
            }
            return false;
        }
    }


}
